package com.webtest.authoritydemo;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/16 15:10
 */
public class AuthorityServlet extends HttpServlet {
    private static final long serialVersionUID = 8564308332625485595L;
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthorityServlet.class);
    private final UserDao userDao = new UserDao();
    private final AuthorityDao authorityDao = new AuthorityDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodName = req.getParameter("method");
        if (StringUtils.isNoneEmpty(methodName)) {
            Method method = null;
            try {
                method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                if (method == null) {
                    return;
                }
                method.invoke(this, req, resp);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                LOGGER.error("invoke error!", e);
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    private void getAuthority(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        if (!userDao.exit(name)) {
            request.setAttribute("message", "用户名不存在，请重新输入");
        } else {
            User user = userDao.get(name);
            request.setAttribute("user", user);
            List<Authority> authorities = authorityDao.getAllAuthority();
            request.setAttribute("authorities", authorities);
        }
        request.getRequestDispatcher("/authdemo/authority_manager.jsp").forward(request, response);
    }

    private void updateAuthority(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("db.username");
        String[] authorities = request.getParameterValues("authority");

        userDao.update(username, authorityDao.getAuthoritiesByIds(Arrays.asList(authorities)));
        request.setAttribute("message", "修改用户信息成功！");
        request.getRequestDispatcher("/authdemo/authority_manager.jsp").forward(request, response);
    }
}
